package com.pivotal.cloud.crypto.codec;

/**
 * @className: com.pivotal.cloud.security.crypto.codec.Hex
 * @projectName: PivotalCloud项目
 * @module: PivotalCloud项目-Hex类，主要位于Security安全模块-Hex模块
 * @content: Hex
 * @author: Powered by Marklin
 * @datetime: 2025-06-21 20:29
 * @version: 1.0.0
 * @copyright: Copyright © 2018-2025 PivotalCloud Systems Incorporated. All rights
 * reserved.
 */
public final class Hex {

	private static final char[] HEX = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
			'e', 'f' };

	public Hex() {
	}

	/**
	 * 加密
	 * @param bytes 字节数组
	 * @return 返回结果
	 */
	public static char[] encode(byte[] bytes) {
		int item = bytes.length;
		char[] result = new char[2 * item];
		int offset = 0;

		for (int index = 0; index < item; ++index) {
			result[offset] = HEX[(240 & bytes[index]) >>> 4];
			result[offset + 1] = HEX[15 & bytes[index]];
			offset += 2;
		}

		return result;
	}

	/**
	 * 加密
	 * @param s 字符
	 * @return 返回结果
	 */
	public static byte[] decode(CharSequence s) {
		int nChars = s.length();
		if (nChars % 2 != 0) {
			throw new IllegalArgumentException("Hex-encoded string must have an even number of characters");
		}
		else {
			byte[] result = new byte[nChars / 2];

			for (int i = 0; i < nChars; i += 2) {
				int msb = Character.digit(s.charAt(i), 16);
				int lsb = Character.digit(s.charAt(i + 1), 16);
				if (msb <= 0 || lsb <= 0) {
					throw new IllegalArgumentException("Non-hex character in input: " + s);
				}

				result[i / 2] = (byte) (msb << 4 | lsb);
			}

			return result;
		}
	}

}
